package com.ruix.app.widget.chatrow;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.os.AsyncTaskCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.model.EaseImageCache;
import com.hyphenate.easeui.utils.EaseImageUtils;
import com.hyphenate.easeui.widget.EaseImageView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowFile;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.ChatAuther;
import com.ruix.app.model.Classes;
import com.ruix.app.util.GlideUitl;
import com.ruix.app.util.PhotoView;

import org.json.JSONObject;

import java.io.File;


/**
 * Created by hadexs on 2017/5/29.
 */

public class ChatRowImage extends EaseChatRowFile {

    protected ImageView imageView;
    private EMImageMessageBody imgBody;
    private TextView autherNameView;
    private TextView autherTagView;
    private EaseImageView userAvatar;

    public ChatRowImage(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflateView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ? com.hyphenate.easeui.R.layout.ease_row_received_picture : com.hyphenate.easeui.R.layout.ease_row_sent_picture, this);
    }


    @Override
    protected void onFindViewById() {
        percentageView = (TextView) findViewById(com.hyphenate.easeui.R.id.percentage);
        imageView = (ImageView) findViewById(com.hyphenate.easeui.R.id.image);
        autherNameView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_name);
        autherTagView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_tag);
        userAvatar = (EaseImageView) findViewById(com.hyphenate.easeui.R.id.iv_userhead);
    }


    @Override
    protected void onSetUpView() {
        handelUserInfo();
        imgBody = (EMImageMessageBody) message.getBody();
        // received messages
//        if (message.direct() == EMMessage.Direct.RECEIVE) {
//            if (imgBody.thumbnailDownloadStatus() == EMFileMessageBody.EMDownloadStatus.DOWNLOADING ||
//                    imgBody.thumbnailDownloadStatus() == EMFileMessageBody.EMDownloadStatus.PENDING) {
//                imageView.setImageResource(com.hyphenate.easeui.R.drawable.ease_default_image);
//                //set the receive message callback
//                setMessageReceiveCallback();
//            } else {
//                progressBar.setVisibility(View.GONE);
//                percentageView.setVisibility(View.GONE);
//                imageView.setImageResource(com.hyphenate.easeui.R.drawable.ease_default_image);
//                String thumbPath = imgBody.thumbnailLocalPath();
//                if (!new File(thumbPath).exists()) {
//                    // to make it compatible with thumbnail received in previous version
//                    thumbPath = EaseImageUtils.getThumbnailImagePath(imgBody.getLocalUrl());
//                }
////                showImageView(thumbPath, imgBody.getLocalUrl(), message);
//            }
//            return;
//        }

        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }

        if (percentageView != null) {
            percentageView.setVisibility(View.GONE);
        }


        if (message.direct() == EMMessage.Direct.SEND) {
            if (message.status() == EMMessage.Status.INPROGRESS) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                if (statusView != null) {
                    statusView.setVisibility(View.GONE);
                }
            } else if (message.status() == EMMessage.Status.FAIL) {
                if (statusView != null) {
                    statusView.setVisibility(View.VISIBLE);
                }
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }else if (message.status() == EMMessage.Status.SUCCESS){
                if (progressBar != null) {
                    progressBar.setVisibility(View.INVISIBLE);
                }
                if (statusView != null) {
                    statusView.setVisibility(View.INVISIBLE);
                }
                String fileUrl = imgBody.getThumbnailUrl();
                showImageView(fileUrl, imageView);
                return;

            }
            String filePath = imgBody.getLocalUrl();
            String thumbPath = EaseImageUtils.getThumbnailImagePath(imgBody.getLocalUrl());
            showImageView(thumbPath, filePath, message);
            return;
        }

        String fileUrl = imgBody.getThumbnailUrl();
        showImageView(fileUrl, imageView);
//        String thumbPath = EaseImageUtils.getThumbnailImagePath(imgBody.getLocalUrl());
//        showImageView(thumbPath, filePath, message);
//        handleSendMessage();
    }

    @Override
    protected void onUpdateView() {
//        super.onUpdateView();
        //获取
    }

    public static void showImageView(String url, ImageView draweeView) {
        if (TextUtils.isEmpty(url)) {
            return;
        }

//        GlideUitl.showImageView();
        Glide.with(RuiApplication.getAppContext()).load(url)
                .thumbnail(0.5f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.ease_default_image_view)
                .error(R.drawable.ease_default_image)
                .fitCenter()
                .into(draweeView);

    }

    protected void onBubbleClick() {
//        Intent intent = new Intent(context, EaseShowBigImageActivity.class);
//        File file = new File(imgBody.getLocalUrl());
//        if (file.exists()) {
//            Uri uri = Uri.fromFile(file);
//            intent.putExtra("uri", uri);
//        } else {
//            // The local full size pic does not exist yet.
//            // ShowBigImage needs to download it from the server
//            // first
//            String msgId = message.getMsgId();
//            intent.putExtra("messageId", msgId);
//            intent.putExtra("localUrl", imgBody.getLocalUrl());
//        }
//        if (message != null && message.direct() == EMMessage.Direct.RECEIVE && !message.isAcked()
//                && message.getChatType() == EMMessage.ChatType.Chat) {
//            try {
//                EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        context.startActivity(intent);
        String fileUrl = imgBody.getRemoteUrl();
        PhotoView.builder()
                .setPhoto(fileUrl)
                .setCurrentItem(0)
                .start(activity);
    }


    private void handelUserInfo() {
        try {
            JSONObject authorObj = message.getJSONObjectAttribute("author");
            if (authorObj != null) {
                String authID = authorObj.optString("id", "");
                ChatAuther chatAuther = UserManager.sharedInstance().getChatAuther(authID);
                if (chatAuther == null) {
                    chatAuther = new ChatAuther();
                    String authName = authorObj.optString("name", "");
                    String roleid = authorObj.optString("role", "");
                    String roleVale = authorRoleValue(roleid);
                    String authAvatar = authorObj.optString("avatar", "");
                    chatAuther.setAuthID(authID);
                    chatAuther.setRoleid(roleid);
                    chatAuther.setAuthName(authName);
                    chatAuther.setRoleVale(roleVale);
                    chatAuther.setAuthAvatar(authAvatar);
                    UserManager.sharedInstance().addChatAuther(chatAuther);
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthName())) {
                    autherNameView.setText(chatAuther.getAuthName());
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthAvatar())) {
                    userAvatar.loadHeaderView(chatAuther.getAuthAvatar());
                }
                if (!TextUtils.isEmpty(chatAuther.getRoleVale())) {
                    autherTagView.setText(chatAuther.getRoleVale());
                    autherTagView.setVisibility(VISIBLE);
                } else {
                    autherTagView.setVisibility(GONE);
                }
            }
        } catch (Exception e) {

        }

    }


    private void showImageView(final String thumbernailPath, final String localFullSizePath,final EMMessage message) {
        // first check if the thumbnail image already loaded into cache
        Bitmap bitmap = EaseImageCache.getInstance().get(thumbernailPath);
        if (bitmap != null) {
            // thumbnail image is already loaded, reuse the drawable
            imageView.setImageBitmap(bitmap);
        } else {
            AsyncTaskCompat.executeParallel(new AsyncTask<Object, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Object... args) {
                    File file = new File(thumbernailPath);
                    if (file.exists()) {
                        return EaseImageUtils.decodeScaleImage(thumbernailPath, 160, 160);
                    } else if (new File(imgBody.thumbnailLocalPath()).exists()) {
                        return EaseImageUtils.decodeScaleImage(imgBody.thumbnailLocalPath(), 160, 160);
                    }
                    else {
                        if (message.direct() == EMMessage.Direct.SEND) {
                            if (localFullSizePath != null && new File(localFullSizePath).exists()) {
                                return EaseImageUtils.decodeScaleImage(localFullSizePath, 160, 160);
                            } else {
                                return null;
                            }
                        } else {
                            return null;
                        }
                    }
                }

                protected void onPostExecute(Bitmap image) {
                    if (image != null) {
                        imageView.setImageBitmap(image);
                        EaseImageCache.getInstance().put(thumbernailPath, image);
                    }
                }
            });
        }
    }

    public String authorRoleValue(String roleID){
        if (!TextUtils.isEmpty(roleID)) {
            if ("1".equals(roleID)){
                return "导师";
            } else if ("5".equals(roleID)){
                return "小助手";
            } else if ("6".equals(roleID)){
                return "嘉宾";
            } else if ("8".equals(roleID)){
                Classes currentClass =  UserManager.sharedInstance().getCurrentClass();
                if (currentClass != null && currentClass.isTeacherFriendCircle()){
                    return "导师";
                }
                return "班主任"; //
            } else if ("9".equals(roleID)){
                return "班委";
            } else if ("10".equals(roleID)){
                return "班长";
            }
        }
        return null;
    }

}
